package Notepad;


public class SimpleNotepad implements INotepad {
	private static final int DEFAULT_NUMBER_OF_PAGES = 10;
	private Page[] pages;

	SimpleNotepad() {
		pages = new Page[DEFAULT_NUMBER_OF_PAGES];
	}

	@Override
	public void addPageText(int pageNum, String text) {
		if (text != null)
			if (isCorrectPageNumber(pageNum)) {
				pageNum--;
				createPageIfNotExists(pageNum);
				pages[pageNum].addText(text);
			}
	}

	@Override
	public void replacePageText(int pageNum, String text) {
		if (text != null)
			if (isCorrectPageNumber(pageNum)) {
				pageNum--;
				createPageIfNotExists(pageNum);
				pages[pageNum].removeText();
				pages[pageNum].addText(text);
			}
	}

	public void removePageText(int pageNum) {
		if (isCorrectPageNumber(pageNum)) {
			createPageIfNotExists(pageNum);
			pages[pageNum - 1].removeText();
		}
	}

	private boolean isCorrectPageNumber(int pageNumber) {
		return pageNumber >= 1 && pageNumber <= DEFAULT_NUMBER_OF_PAGES;
	}

	private void createPageIfNotExists(int pageNumber) {
		// Lazy loading - allocates memory for page
		if (pages[pageNumber] == null)
			pages[pageNumber] = new Page("Page" + pageNumber);
	}

	@Override
	public void printNotepad() {
		System.out.println(this);
	}

	public String toString() {
		String s = "";
		for (Page page : pages) {
			if (page != null) {
				s += page.getPageContent() + "\n" + "\n";
			}
		}
		return s;
	}

	@Override
	public boolean searchWord(String word) {
		boolean isFound = false;

		for (int i = 0; i < pages.length; i++) {
			if (pages[i] != null)
				if (pages[i].searchWord(word) == true)
					isFound = true;
				else
					isFound = false;
		}
		return isFound;
	}

	@Override
	public void printAllPagesWithDigits() {
		for (Page page : pages) {
			if (page != null && page.containsDigits()) {
				System.out.println(page.getPageContent());
			}
		}

	}
}
